﻿using Microsoft.Extensions.Options;
using RuoVea.ExLog;


namespace RuoVea.Iot.MqttClient.Server;

/// <summary>
/// 使用 MQTT 服务的后台任务
/// </summary>
public class MqttBackgroundService : BackgroundService
{
    private readonly MqttClientService _mqttService;
    private readonly IOptions<MqttOptions> _options;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="mqttService"></param>
    /// <param name="options"></param>

    public MqttBackgroundService(MqttClientService mqttService, IOptions<MqttOptions> options)
    {
        _mqttService = mqttService;
        _options = options;
    }

    /// <summary>
    /// 执行后台任务
    /// </summary>
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // 定期检查连接状态
            bool isConnected = MqttClientService._mqttClient?.IsConnected ?? false;
            LogFactory.Info($"MQTT 连接状态: {isConnected}");
            // 定期发送心跳消息
            if (isConnected)
            {
                LogFactory.Info($"健康检查,时间{DateTime.Now} 【{_options.Value.ClientId}】【{_options.Value.Server}】");
                //await _mqttService.Publish("Heartbeat", Data:$"健康检查,时间{DateTime.Now}");
            }
            await Task.Delay(_options.Value.HeartbeatInterval * 1000, stoppingToken);
        }
    }
}
